<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
<script src="https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js"></script>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/picture/pika.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/picture/pika.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="code-LqqDM3vffE">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">


  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/2efd5eff.js","daovoice")
  daovoice('init', {
    app_id: "2efd5eff"
  });
  daovoice('update');
  </script>


<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"notspr.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":true,"color":"#ff7600","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="Django ORM Django 模型使用自带的 ORM。 对象关系映射（Object Relational Mapping，简称 ORM ）用于实现面向对象编程语言里不同类型系统的数据之间的转换。 ORM 在业务逻辑层和数据库层之间充当了桥梁的作用。 ORM 是通过使用描述对象和数据库之间的映射的元数据，将程序中的对象自动持久化到数据库中。">
<meta property="og:type" content="article">
<meta property="og:title" content="Django之ORM操作">
<meta property="og:url" content="https://notspr.com/2020/03/21/django-orm/index.html">
<meta property="og:site_name" content="Sapphire">
<meta property="og:description" content="Django ORM Django 模型使用自带的 ORM。 对象关系映射（Object Relational Mapping，简称 ORM ）用于实现面向对象编程语言里不同类型系统的数据之间的转换。 ORM 在业务逻辑层和数据库层之间充当了桥梁的作用。 ORM 是通过使用描述对象和数据库之间的映射的元数据，将程序中的对象自动持久化到数据库中。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://notspr.com/2020/03/21/django-orm/django-orm1.png">
<meta property="og:image" content="https://notspr.com/2020/03/21/django-orm/orm-object.png">
<meta property="article:published_time" content="2020-03-20T19:07:42.000Z">
<meta property="article:modified_time" content="2020-12-02T17:40:47.250Z">
<meta property="article:author" content="Ryan Shu">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="数据库">
<meta property="article:tag" content="Django">
<meta property="article:tag" content="ORM">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://notspr.com/2020/03/21/django-orm/django-orm1.png">

<link rel="canonical" href="https://notspr.com/2020/03/21/django-orm/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Django之ORM操作 | Sapphire</title>
  


  <script data-pjax>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?2907d577c8c6c2f7fe3843736d24280d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <!--pjax：防止跳转页面音乐暂停-->
  <script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.js"></script>
<link rel="alternate" href="/atom.xml" title="Sapphire" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Sapphire</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">興趣使然的博客</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/aboutme/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">82</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">34</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">40</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/sususama5555" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://notspr.com/2020/03/21/django-orm/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/picture/avatar.jpg">
      <meta itemprop="name" content="Ryan Shu">
      <meta itemprop="description" content="全栈 | 硬件 | 篮球 | 游戏">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sapphire">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Django之ORM操作
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-03-21 03:07:42" itemprop="dateCreated datePublished" datetime="2020-03-21T03:07:42+08:00">2020-03-21</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Django/" itemprop="url" rel="index"><span itemprop="name">Django</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Django/ORM/" itemprop="url" rel="index"><span itemprop="name">ORM</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.1k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>3 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <blockquote>
<h1 id="Django-ORM"><a href="#Django-ORM" class="headerlink" title="Django ORM"></a>Django ORM</h1></blockquote>
<p>Django 模型使用自带的 ORM。</p>
<p><kbd>对象关系映射</kbd>（Object Relational Mapping，简称 ORM ）用于实现面向对象编程语言里不同类型系统的数据之间的转换。</p>
<p>ORM 在业务逻辑层和数据库层之间充当了桥梁的作用。</p>
<p>ORM 是通过使用描述对象和数据库之间的映射的元数据，将程序中的对象自动持久化到数据库中。</p>
<img data-src="/2020/03/21/django-orm/django-orm1.png" class>

<a id="more"></a>

<h2 id="使用-ORM-的好处："><a href="#使用-ORM-的好处：" class="headerlink" title="使用 ORM 的好处："></a>使用 ORM 的好处：</h2><ul>
<li>提高开发效率。</li>
<li>不同数据库可以平滑切换。</li>
</ul>
<h2 id="使用-ORM-的缺点："><a href="#使用-ORM-的缺点：" class="headerlink" title="使用 ORM 的缺点："></a>使用 ORM 的缺点：</h2><ul>
<li>ORM 代码转换为 SQL 语句时，需要花费一定的时间，执行效率会有所降低。</li>
<li>长期写 ORM 代码，会降低编写 SQL 语句的能力。</li>
</ul>
<h2 id="ORM-解析过程"><a href="#ORM-解析过程" class="headerlink" title="ORM 解析过程:"></a>ORM 解析过程:</h2><ul>
<li>1、ORM 会将 Python 代码转成为 SQL 语句。</li>
<li>2、SQL 语句通过 pymysql 传送到数据库服务端。</li>
<li>3、在数据库中执行 SQL 语句并将结果返回。</li>
</ul>
<h2 id="ORM-对应关系表："><a href="#ORM-对应关系表：" class="headerlink" title="ORM 对应关系表："></a>ORM 对应关系表：</h2><img data-src="/2020/03/21/django-orm/orm-object.png" class>

<h1 id="查询类操作"><a href="#查询类操作" class="headerlink" title="查询类操作"></a>查询类操作</h1><h2 id="查询所有的结果"><a href="#查询所有的结果" class="headerlink" title="查询所有的结果"></a>查询所有的结果</h2><p>相当sql中的select * from</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">list = Test.objects.all()</span><br></pre></td></tr></table></figure>

<h2 id="条件查询filter相关sql中的where"><a href="#条件查询filter相关sql中的where" class="headerlink" title="条件查询filter相关sql中的where"></a>条件查询filter相关sql中的where</h2><p>用于过滤查询结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">result = Test.objects.filter(id=<span class="number">1</span>, name=’test’) <span class="comment"># 传多个参数</span></span><br></pre></td></tr></table></figure>

<p>如果多条件与查询，直接用逗号隔开，filter函数里面的参数都是Test Model中的字段</p>
<h2 id="获取单个对象"><a href="#获取单个对象" class="headerlink" title="获取单个对象"></a>获取单个对象</h2><p>get方法的参数一般为Model的主键，如果找不到会报错</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">test_obj = Test.objects.get(id=<span class="number">1</span>)</span><br></pre></td></tr></table></figure>

<h2 id="限制返回的结果数据的数量"><a href="#限制返回的结果数据的数量" class="headerlink" title="限制返回的结果数据的数量"></a>限制返回的结果数据的数量</h2><p>相当于sql中的limit，其中order_by是用于排序，如果根据字段a倒序排序，就是order_by(“-time”)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Test.objects.order_by(<span class="string">'name'</span>)[<span class="number">0</span>:<span class="number">2</span>]</span><br></pre></td></tr></table></figure>

<h2 id="链式查询"><a href="#链式查询" class="headerlink" title="链式查询"></a>链式查询</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Test.objects.filter(name=’test’).order_by(“-ctime”)</span><br></pre></td></tr></table></figure>

<h2 id="多条件参数查询"><a href="#多条件参数查询" class="headerlink" title="多条件参数查询"></a>多条件参数查询</h2><p>传字典，构造查询条件</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">data = Test.objects.filter(**query_dict).order_by(“-ctime”).values</span><br></pre></td></tr></table></figure>

<p>其中query_dict为一个字典，key为条件字段，value为条件值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">query_dict = &#123;<span class="string">'id'</span>:<span class="number">123</span>,<span class="string">'name'</span>:’yyp’&#125;</span><br></pre></td></tr></table></figure>

<h2 id="传Q对象"><a href="#传Q对象" class="headerlink" title="传Q对象"></a>传Q对象</h2><h3 id="构造查询条件"><a href="#构造查询条件" class="headerlink" title="构造查询条件"></a>构造查询条件</h3><ol>
<li><p>在 filter() 等函式中关键字参数彼此之间都是 “and” 关系。但是要执行更复杂的查询(比如，实现筛选条件的 or 关系)，可以使用 Q 对象。</p>
</li>
<li><p>Q对象包括 AND 关系和OR 关系</p>
</li>
<li><p>Q 对象可以用&amp;和 | 运算符进行连接。当某个操作连接两个 Q 对象时，就会产生一个新的等价的 Q 对象。</p>
<ul>
<li>第一步，构造Q对象：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.db.models <span class="keyword">import</span> Q</span><br><span class="line">Q(name__startswith=’h’) | Q(name__startswith=’p’)</span><br></pre></td></tr></table></figure></li>
<li>第二步，Q对象以查询参数方式使用，多个Q对象是and关系:<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Test.objects.filter(</span><br><span class="line">Q(date=’<span class="number">2018</span><span class="number">-10</span><span class="number">-10</span> <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span>’),</span><br><span class="line">Q(name__startswith=’h’) | Q(name__startswith=’p’)</span><br></pre></td></tr></table></figure>

</li>
</ul>
</li>
</ol>
<blockquote>
<p>filter() 等函数可以接受 Q对象和条件参数，但Q对象必须放在条件参数前面 </p>
</blockquote>
<h3 id="传入条件查询"><a href="#传入条件查询" class="headerlink" title="传入条件查询"></a>传入条件查询</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">q1 = Q()</span><br><span class="line">q1.connector = <span class="string">'OR'</span>              <span class="comment">#连接方式</span></span><br><span class="line">q1.children.append((<span class="string">'id'</span>, <span class="number">1</span>))</span><br><span class="line">q1.children.append((<span class="string">'id'</span>, <span class="number">2</span>))</span><br><span class="line">q1.children.append((<span class="string">'id'</span>, <span class="number">3</span>))</span><br><span class="line"></span><br><span class="line">models.Tb1.objects.filter(q1)</span><br></pre></td></tr></table></figure>



<h3 id="合并条件查询"><a href="#合并条件查询" class="headerlink" title="合并条件查询"></a>合并条件查询</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">con = Q()</span><br><span class="line"></span><br><span class="line">q1 = Q()</span><br><span class="line">q1.connector = <span class="string">'OR'</span></span><br><span class="line">q1.children.append((<span class="string">'id'</span>, <span class="number">1</span>))</span><br><span class="line">q1.children.append((<span class="string">'id'</span>, <span class="number">2</span>))</span><br><span class="line">q1.children.append((<span class="string">'id'</span>, <span class="number">3</span>))</span><br><span class="line"></span><br><span class="line">q2 = Q()</span><br><span class="line">q2.connector = <span class="string">'OR'</span></span><br><span class="line">q2.children.append((<span class="string">'status'</span>, <span class="string">'在线'</span>))</span><br><span class="line"></span><br><span class="line">con.add(q1, <span class="string">'AND'</span>)</span><br><span class="line">con.add(q2, <span class="string">'AND'</span>)</span><br><span class="line"></span><br><span class="line">models.Tb1.objects.filter(con)</span><br></pre></td></tr></table></figure>



<h2 id="过滤不满足条件的操作"><a href="#过滤不满足条件的操作" class="headerlink" title="过滤不满足条件的操作"></a>过滤不满足条件的操作</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">data = Test.objects.exclude(id=<span class="number">1</span>)</span><br></pre></td></tr></table></figure>



<h1 id="增加类操作"><a href="#增加类操作" class="headerlink" title="增加类操作"></a>增加类操作</h1><h2 id="新增一条记录"><a href="#新增一条记录" class="headerlink" title="新增一条记录"></a>新增一条记录</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">test1 = Test(name=<span class="string">'yyp'</span>)</span><br><span class="line">test1.save()</span><br></pre></td></tr></table></figure>



<h1 id="更新类操作"><a href="#更新类操作" class="headerlink" title="更新类操作"></a>更新类操作</h1><h2 id="先查询获取对象，再修改对象的值，再保存"><a href="#先查询获取对象，再修改对象的值，再保存" class="headerlink" title="先查询获取对象，再修改对象的值，再保存"></a>先查询获取对象，再修改对象的值，再保存</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">test1 = Test.objects.get(id=<span class="number">1</span>)</span><br><span class="line">test1.name = <span class="string">'Google'</span></span><br><span class="line">test1.save()</span><br></pre></td></tr></table></figure>



<h2 id="条件链式更新"><a href="#条件链式更新" class="headerlink" title="条件链式更新"></a>条件链式更新</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Test.objects.filter(id=<span class="number">1</span>).update(name=‘Google’)</span><br></pre></td></tr></table></figure>



<h1 id="删除类操作"><a href="#删除类操作" class="headerlink" title="删除类操作"></a>删除类操作</h1><h2 id="先查询获取要删除的对象，然后直接delete操作"><a href="#先查询获取要删除的对象，然后直接delete操作" class="headerlink" title="先查询获取要删除的对象，然后直接delete操作"></a>先查询获取要删除的对象，然后直接delete操作</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 删除id=1的数据</span></span><br><span class="line">test1 = Test.objects.get(id=<span class="number">1</span>)</span><br><span class="line">test1.delete()</span><br></pre></td></tr></table></figure>

<h2 id="条件删除："><a href="#条件删除：" class="headerlink" title="条件删除："></a>条件删除：</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Test.objects.filter(id=<span class="number">1</span>).delete()</span><br></pre></td></tr></table></figure>

<h2 id="QuerySet相关"><a href="#QuerySet相关" class="headerlink" title="QuerySet相关"></a>QuerySet相关</h2><p>Django中model查询出来的结构类型为QuerySet，本质是一个查询对象集。</p>
<h2 id="将多个查询结果转换为字典列表"><a href="#将多个查询结果转换为字典列表" class="headerlink" title="将多个查询结果转换为字典列表"></a>将多个查询结果转换为字典列表</h2><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># all()方法查询出来的是QuerySet，用values方法转成字典集</span></span><br><span class="line">data= Test.objects.all().values()</span><br><span class="line">data_dict_list = list(data)</span><br><span class="line">&lt;QuerySet [&lt;Test:  test&gt;]&gt;    ----&gt;&lt;QuerySet [&#123;“id”:XXX, “name”:XXX&#125;]&gt;</span><br></pre></td></tr></table></figure>



<h2 id="QuerySet对象转换成字典对象"><a href="#QuerySet对象转换成字典对象" class="headerlink" title="QuerySet对象转换成字典对象"></a>QuerySet对象转换成字典对象</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fromdjango.forms.models <span class="keyword">import</span> model_to_dict</span><br><span class="line">data = Test.objects.get(id=<span class="number">1</span>)</span><br><span class="line">data_dict = model_to_dict(data)</span><br></pre></td></tr></table></figure>

<h2 id="序列化成json数据"><a href="#序列化成json数据" class="headerlink" title="序列化成json数据"></a>序列化成json数据</h2><p>对于很多web开发接口的时候，要返回的是json数据，而django从DB查询出来的是对象集，可以考虑django-rest-framework 库的serializers类，具体可参考：<a href="https://q1mi.github.io/Django-REST-framework-documentation/tutorial/1-serialization_zh/" target="_blank" rel="noopener"><strong>Tutorial 1: 序列化</strong></a></p>
<h1 id="查询条件总结"><a href="#查询条件总结" class="headerlink" title="查询条件总结"></a>查询条件总结</h1><h2 id="字段名-op"><a href="#字段名-op" class="headerlink" title="字段名__op:"></a>字段名__op:</h2><p>__exact 精确等于 like ‘aaa’</p>
<p>__iexact精确等于忽略大小写ilike‘aaa’</p>
<p>__contains 包含 like ‘%aaa%’</p>
<p>__icontains包含忽略大小写ilike‘%aaa%’，但是对于sqlite来说，contains的作用效果等同于icontains。</p>
<p>__gt大于</p>
<p>__gte大于等于</p>
<p>__lt小于</p>
<p>__lte小于等于</p>
<p>__in 存在于一个list范围内</p>
<p>__startswith以…开头</p>
<p>__istartswith以…开头忽略大小写</p>
<p>__endswith以…结尾</p>
<p>__iendswith以…结尾，忽略大小写</p>
<p>__range 在…范围内</p>
<p>__year 日期字段的年份</p>
<p>__month 日期字段的月份</p>
<p>__day 日期字段的日</p>
<p>__isnull=True/False</p>
<h2 id="使用sql语句进行查询："><a href="#使用sql语句进行查询：" class="headerlink" title="使用sql语句进行查询："></a>使用sql语句进行查询：</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">fromdjango.db <span class="keyword">import</span> connection</span><br><span class="line">cursor = connection.cursor()</span><br><span class="line">cursor.execute(“select * <span class="keyword">from</span> Test where name = %s”, <span class="string">"yyp"</span>)</span><br><span class="line">row = cursor.fetchone()</span><br></pre></td></tr></table></figure>



<hr>
<p>参考链接：<br><a href="https://mp.weixin.qq.com/s/okaGAbNkFLhwZXvZV7eUBw" target="_blank" rel="noopener">【经验分享】Django开发中常用到的数据库操作总结</a> </p>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Ryan Shu
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://notspr.com/2020/03/21/django-orm/" title="Django之ORM操作">https://notspr.com/2020/03/21/django-orm/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/picture/weixin.png">
            <span class="icon">
              <i class="fab fa-weixin"></i>
            </span>

            <span class="label">WeChat</span>
          </a>
        </div>

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
              <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/" rel="tag"><i class="fa fa-tag"></i> 数据库</a>
              <a href="/tags/Django/" rel="tag"><i class="fa fa-tag"></i> Django</a>
              <a href="/tags/ORM/" rel="tag"><i class="fa fa-tag"></i> ORM</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/03/18/python-thread-process/" rel="prev" title="Python之多线程与多进程">
      <i class="fa fa-chevron-left"></i> Python之多线程与多进程
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/04/03/go-basis-exercise-1/" rel="next" title="Go语言基础练习一">
      Go语言基础练习一 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Django-ORM"><span class="nav-number">1.</span> <span class="nav-text">Django ORM</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用-ORM-的好处："><span class="nav-number">1.1.</span> <span class="nav-text">使用 ORM 的好处：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用-ORM-的缺点："><span class="nav-number">1.2.</span> <span class="nav-text">使用 ORM 的缺点：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ORM-解析过程"><span class="nav-number">1.3.</span> <span class="nav-text">ORM 解析过程:</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ORM-对应关系表："><span class="nav-number">1.4.</span> <span class="nav-text">ORM 对应关系表：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#查询类操作"><span class="nav-number">2.</span> <span class="nav-text">查询类操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#查询所有的结果"><span class="nav-number">2.1.</span> <span class="nav-text">查询所有的结果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#条件查询filter相关sql中的where"><span class="nav-number">2.2.</span> <span class="nav-text">条件查询filter相关sql中的where</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#获取单个对象"><span class="nav-number">2.3.</span> <span class="nav-text">获取单个对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#限制返回的结果数据的数量"><span class="nav-number">2.4.</span> <span class="nav-text">限制返回的结果数据的数量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#链式查询"><span class="nav-number">2.5.</span> <span class="nav-text">链式查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多条件参数查询"><span class="nav-number">2.6.</span> <span class="nav-text">多条件参数查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#传Q对象"><span class="nav-number">2.7.</span> <span class="nav-text">传Q对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#构造查询条件"><span class="nav-number">2.7.1.</span> <span class="nav-text">构造查询条件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#传入条件查询"><span class="nav-number">2.7.2.</span> <span class="nav-text">传入条件查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#合并条件查询"><span class="nav-number">2.7.3.</span> <span class="nav-text">合并条件查询</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#过滤不满足条件的操作"><span class="nav-number">2.8.</span> <span class="nav-text">过滤不满足条件的操作</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#增加类操作"><span class="nav-number">3.</span> <span class="nav-text">增加类操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#新增一条记录"><span class="nav-number">3.1.</span> <span class="nav-text">新增一条记录</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#更新类操作"><span class="nav-number">4.</span> <span class="nav-text">更新类操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#先查询获取对象，再修改对象的值，再保存"><span class="nav-number">4.1.</span> <span class="nav-text">先查询获取对象，再修改对象的值，再保存</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#条件链式更新"><span class="nav-number">4.2.</span> <span class="nav-text">条件链式更新</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#删除类操作"><span class="nav-number">5.</span> <span class="nav-text">删除类操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#先查询获取要删除的对象，然后直接delete操作"><span class="nav-number">5.1.</span> <span class="nav-text">先查询获取要删除的对象，然后直接delete操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#条件删除："><span class="nav-number">5.2.</span> <span class="nav-text">条件删除：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#QuerySet相关"><span class="nav-number">5.3.</span> <span class="nav-text">QuerySet相关</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#将多个查询结果转换为字典列表"><span class="nav-number">5.4.</span> <span class="nav-text">将多个查询结果转换为字典列表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#QuerySet对象转换成字典对象"><span class="nav-number">5.5.</span> <span class="nav-text">QuerySet对象转换成字典对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#序列化成json数据"><span class="nav-number">5.6.</span> <span class="nav-text">序列化成json数据</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#查询条件总结"><span class="nav-number">6.</span> <span class="nav-text">查询条件总结</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#字段名-op"><span class="nav-number">6.1.</span> <span class="nav-text">字段名__op:</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用sql语句进行查询："><span class="nav-number">6.2.</span> <span class="nav-text">使用sql语句进行查询：</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Ryan Shu"
      src="/picture/avatar.jpg">
  <p class="site-author-name" itemprop="name">Ryan Shu</p>
  <div class="site-description" itemprop="description">全栈 | 硬件 | 篮球 | 游戏</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">40</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">82</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/sususama5555" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sususama5555" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:876324872@qq.com" title="E-Mail → mailto:876324872@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/5330189327" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;5330189327" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://steamcommunity.com/profiles/76561198294148424/" title="steam → https:&#x2F;&#x2F;steamcommunity.com&#x2F;profiles&#x2F;76561198294148424&#x2F;" rel="noopener" target="_blank"><i class="fab fa-steam fa-fw"></i>steam</a>
      </span>
      <span class="links-of-author-item">
        <a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-rss fa-fw"></i>RSS</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://ddoudou.xyz/" title="http:&#x2F;&#x2F;ddoudou.xyz" rel="noopener" target="_blank">豆豆的博客</a>
        </li>
    </ul>
  </div>

      </div>

      <!-- 音乐播放器 -->
      
           <div>
              <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="210" height="110" src="//music.163.com/outchain/player?type=2&id=4226232&auto=1&height=66"></iframe>
           </div>
      

      <!-- 滚动条 -->
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">粤ICP备20063016号-2 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ryan Shu</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">180k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">2:44</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  
  <script data-pjax>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

    </div>
</body>
</html>
